package com.wetao.lib_common.common.ui;

import android.text.InputType;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.gyf.immersionbar.BarHide;
import com.gyf.immersionbar.ImmersionBar;
import com.wetao.lib_common.ConstantArouter;
import com.wetao.lib_common.R;
import com.wetao.lib_common.R2;
import com.wetao.lib_common.base.Base2Response;
import com.wetao.lib_common.base.BaseActivity;
import com.wetao.lib_common.base.BaseResponse;
import com.wetao.lib_common.common.contract.PwdResetContract;
import com.wetao.lib_common.common.presenter.PwdResetPresenter;
import com.wetao.lib_common.tsdBlePen.TsdService;
import com.wetao.lib_common.utils.BaseEvent;
import com.wetao.lib_common.utils.ComUtil;
import com.wetao.lib_common.utils.LogUtils;
import com.wetao.lib_common.utils.ToastUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

/**
 * 所有模块统一注册页面
 */
@Route(path = ConstantArouter.PATH_COMMON_PWDRESETACTIVITY)
public class Common_PwdResetActivity extends BaseActivity<PwdResetContract.View, PwdResetContract.Presenter> implements
        PwdResetContract.View {

    @Autowired
    String targetUrl;
    @Autowired
    String phone;

    @BindView(R2.id.et_reset_account)
    EditText et_reset_account;
    @BindView(R2.id.et_verification_code)
    EditText et_verification_code;
    @BindView(R2.id.tv_get_code)
    TextView tv_get_code;
    @BindView(R2.id.et_new_pass)
    EditText et_new_pass;
    @BindView(R2.id.iv_eye)
    ImageView iv_eye;
    @BindView(R2.id.et_re_new_pass)
    EditText et_re_new_pass;
    @BindView(R2.id.iv_re_eye)
    ImageView iv_re_eye;
    @BindView(R2.id.btn_submit)
    Button btn_submit;

    private Disposable disposable;

    private boolean eyeOpen = false;
    private boolean eyeOpenReset = false;

    private final int count = 60;//验证码倒计时


    @Override
    public int getLayoutId() {
        return R.layout.activity_reset_pass;
    }

    @Override
    public boolean getIsBindTsdService() {
        return false;
    }

    @Override
    public TsdService.OnDataReceiveListener getTsdServiceDataReceiveListener() {
        return null;
    }

    @Override
    public void setImmersionBar() {
        ImmersionBar.with(this).reset();
        ImmersionBar.with(this)
                .transparentBar()
                .hideBar(BarHide.FLAG_HIDE_NAVIGATION_BAR)
                .init();
    }

    @Override
    public PwdResetContract.Presenter createPresenter() {
        return new PwdResetPresenter(this);
    }

    @Override
    public PwdResetContract.View createView() {
        return this;
    }

    @Override
    public void init() {
        if(!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        et_new_pass.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
        et_re_new_pass.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
        if(phone != null) {
            et_reset_account.setText(phone.trim());
        }

        et_reset_account.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
        et_verification_code.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);

    }




    private void initTimer() {
        Observable.interval(0, 1, TimeUnit.SECONDS)//设置0延迟，每隔一秒发送一条数据
                .take(count+1) //设置发送count+1次 因为是count~0秒
                .map(new Function<Long, Long>() {
                    @Override
                    public Long apply(Long aLong) throws Exception {
                        LogUtils.d("apply"+(count-aLong));
                        return count-aLong; //发送倒计时
                    }
                })
                .doOnSubscribe(new Consumer<Disposable>() {// 观察者订阅时调用
                    @Override
                    public void accept(Disposable disposable){
                        tv_get_code.setEnabled(false);//在发送数据的时候设置为可以跳过
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())//操作UI要在UI线程
                .subscribe(new Observer<Long>() {
                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();

                    }

                    @Override
                    public void onComplete() {
                        LogUtils.d("onCompleted: "+System.currentTimeMillis());
                        tv_get_code.setEnabled(true);
                        tv_get_code.setText("获取验证码");
                    }

                    @Override
                    public void onSubscribe(Disposable d) {
                        tv_get_code.setText("倒计时" + count + " s");
                        disposable = d;
                    }

                    @Override
                    public void onNext(Long aLong) { //接受到一条就是会操作一次UI
                        LogUtils.d("onNext: "+aLong);
                        tv_get_code.setText("倒计时" + aLong + " s");
                    }
                });
    }

    @Override
    public void getResetPwdResult(Base2Response data) {
        ToastUtil.initToast("密码找回成功");
        finish();
    }


    @Override
    public void getVerifyCodeResult(BaseResponse data) {
        if (data.getCode() == 0){
            initTimer();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onEventReceived(BaseEvent event) {
        if(event.getCode() == 0){
            finish();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }

        if(disposable != null){
            disposable.dispose();
        }
    }
    @OnClick({
            R2.id.ll_back,
            R2.id.iv_eye,
            R2.id.iv_re_eye,
            R2.id.tv_get_code,
            R2.id.btn_submit,
    })
    public void onViewClick(View view) {
        if(view.getId() == R.id.tv_get_code) {
            String phone = et_reset_account.getText().toString();
            if(!TextUtils.isEmpty(phone)) {
                if (ComUtil.isNetworkConnected()){
                    getPresenter().getVerifyCode(ComUtil.getHashmapByStr(new String[]{"account"}, new String[]{phone.trim()}), false, true);
                }else {
                    ToastUtil.initToast(getString(R.string.network_disconnect));
                }
            }else{
                ToastUtil.initToast("请输入有效手机号码！");
            }
        }else if(view.getId() == R.id.iv_eye){
            eyeOpen = !eyeOpen;
            if(eyeOpen) {
                iv_eye.setImageResource(R.drawable.common_login_eye_open);
                et_new_pass.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
            } else {
                iv_eye.setImageResource(R.drawable.common_login_eye_close);
                et_new_pass.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
            }
        }else if(view.getId() == R.id.iv_re_eye){
            eyeOpenReset = !eyeOpenReset;
            if(eyeOpenReset) {
                iv_re_eye.setImageResource(R.drawable.common_login_eye_open);
                et_re_new_pass.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
            } else {
                iv_re_eye.setImageResource(R.drawable.common_login_eye_close);
                et_re_new_pass.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
            }
        } else if(view.getId() == R.id.btn_submit){
            String password = et_new_pass.getText().toString().trim();
            String passwordRe = et_re_new_pass.getText().toString().trim();
            String code = et_verification_code.getText().toString().trim();

            phone = et_reset_account.getText().toString().trim();
            if (phone.isEmpty()){
                ToastUtil.initToast("请输入手机号码");
                return;
            }

            if (code.isEmpty()){
                ToastUtil.initToast("请输入验证码");
                return;
            }

            if (password.isEmpty() || passwordRe.isEmpty()) {
                ToastUtil.initToast("请输入密码");
                return;
            }
            if (!password.equals(passwordRe)) {
                ToastUtil.initToast("请输入相同密码");
                return;
            }

            if(!ComUtil.validatePass(password)) {
                ToastUtil.initToast("请输入8-16数字+字母组合的新密码");
                return;
            }


            getPresenter().getResetPwd(ComUtil.getHashmapByStr(
                    new String[]{"account", "verifyCode", "password"},
                    new String[]{phone, code, password})
                    , false, false);
        }else if(view.getId() == R.id.ll_back) {
            finish();
        }
    }


}
